package top.boycharse.blog.dao.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import top.boycharse.blog.dao.bean.Label;
import top.boycharse.blog.dao.repository.LabelRepository;

import javax.transaction.Transactional;
import java.util.List;
import java.util.Optional;

@Service
public class LabelService {

    @Autowired
    private LabelRepository labelRepository;

    /**
     * 根据名称查label
     * @param labelName
     * @return
     */
    public Label findByLabelName(String labelName) {
        Label label = labelRepository.findByLabelName(labelName);
        return label;
    }

    @Transactional
    public Label saveLabel(Label label) {
        return labelRepository.save(label);
    }

    @Transactional
    public Label findByLabelId(Integer id) {
        Optional<Label> label = labelRepository.findById(id);
        if (label.isPresent()) {
            return label.get();
        }else {
            return null;
        }
    }

    /**
     * 删除标签
     * @param label
     */
    @Transactional
    public void deleteLabel(Label label) {
        labelRepository.delete(label);
    }

    @Transactional
    public void updateLabelName(Label label,String name) {
        if (label != null) {
            label.setLabelName(name);
        }
    }

    /**
     * 查询user对应的所有标签
     * @param username
     * @return List<Label>
     */
    public List<Label> findLabelByUsername(String username) {
        List<Label> labels = labelRepository.findByUser_UserName(username);
        return labels;
    }
}
